package com.boco.ibssystem.common.result.support;

import com.alibaba.fastjson.JSONObject;
import com.boco.ibssystem.common.RequestContextHolderUtil;
import com.boco.ibssystem.common.aop.RestControllerAspect;
import com.boco.ibssystem.common.interceptor.ResponseResultInterceptor;
import com.boco.ibssystem.common.result.AbstractResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        ResponseResult responseResultAnn = (ResponseResult) RequestContextHolderUtil.getRequest().getAttribute(ResponseResultInterceptor.RESPONSE_RESULT);
        return responseResultAnn == null ? false : true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        ResponseResult responseResultAnn = (ResponseResult) RequestContextHolderUtil.getRequest().getAttribute(ResponseResultInterceptor.RESPONSE_RESULT);

        Class<? extends AbstractResult> resultClazz = responseResultAnn.value();

        if (resultClazz.isAssignableFrom(AbstractResult.class)) {
            if (body instanceof FailtureResult) {
                FailtureResult defaultErrorResult = (FailtureResult) body;
                defaultErrorResult.setParams((String) RequestContextHolderUtil.getRequest().getAttribute(RestControllerAspect.REQUEST_PARAMS));
                return defaultErrorResult;
            }
            if (body instanceof String) {
                RequestContextHolderUtil.getResponse().setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                return JSONObject.toJSONString(SuccessResult.success(body));
            }
            return SuccessResult.success(body);
        }

        return body;
    }
}
